<?php

namespace app\adminapi\service;

use app\adminapi\dto\sysuser\LoginRepVO;
use app\adminapi\dto\sysuser\LoginReqVO;
use app\adminapi\model\sysrole\SysRoleDO;
use app\adminapi\model\sysuser\SysUserDO;
use app\common\cache\AdminTokenCache;
use app\common\exception\OtherException;
use app\common\utils\JWTUtils;
use app\common\utils\PasswordUtil;
use think\Db;

class SysRoleService
{
    public function list(array $param)
    {
        $where = [];
        if (isset($param['roleName'])) {
            $where[] = ['role_name', 'like', '%' . $param['roleName'] . '%'];
        }
        if (isset($param['timeArr'])) {
            $where[] = ['create_time', 'between', $param['timeArr']];
        }
        $paginate['list_rows'] = $param['pageSize'];
        if (isset($param['pageNo'])) {
            $paginate['page'] = $param['pageNo'];
        }
        $result = (new SysRoleDO())
            ->where($where)
            ->paginate($paginate)
            ->toArray();
        return [
            'total' => $result['total'],
            'list' => $result['data']
        ];
    }

    public function addSysRole(array $sysRoleDO)
    {
        $this->validRoleCodeExist($sysRoleDO['roleCode'], []);
        SysRoleDO::create($sysRoleDO);
    }

    public function deleteSysRole(int $roleId)
    {
        $model = new SysRoleDO();
        $this->validExist($roleId);
        $model->startTrans();
        try {
            (new SysRoleMenuService())->deleteSysRoleMenuByRoleId($roleId);
            $model::destroy(['id' => $roleId]);
            $model->commit();
            return 1;
        } catch (\Exception $e) {
            $model->rollback();
            throw new OtherException($e->getMessage());
        }
    }

    public function getSysRole(int $roleId)
    {
        $this->validExist($roleId);
        return (new SysRoleDO())->where('id', $roleId)->find();
    }

    public function updateSysRole(array $sysRoleDO)
    {
        $this->validExist($sysRoleDO['id']);
        $this->validRoleCodeExist($sysRoleDO['roleCode'], $sysRoleDO);
        return SysRoleDO::update($sysRoleDO);
    }

    private function validExist(int $roleId)
    {
        $exist = (new SysRoleDO())->where('id', $roleId)->find();
        if (empty($exist)) {
            throw new OtherException('角色不存在');
        }
    }

    private function validRoleCodeExist(string $roleCode, array $oldInfo)
    {
        $where[] = ['role_code', '=', $roleCode];
        if (!empty($oldInfo)) {
            $where[] = ['id', '<>', $oldInfo['id']];
        }
        $exist = (new SysRoleDO())->where($where)->find();
        if (!empty($exist)) {
            throw new OtherException('角色编码已存在');
        }
    }
}